package com.xnj.testweb.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.xnj.testweb.common.exeception.CommonException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
public class ExcelUtils {


    public static <T> void exportExcel(HttpServletResponse response, String fileName, Class<T> head, List<T> data) throws IOException {
        if (data == null) {
            data = new ArrayList<>();
        }
        StringBuilder sb = new StringBuilder(fileName);
//        sb.append("-").append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH.mm.ss.SSS")));
        sb.append("-").append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmm")));
        fileName = sb.toString();
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里 URLEncoder.encode 可以防止中文乱码 当然和 easyexcel 没有关系
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");
        // 这里需要设置不关闭流
        HorizontalCellStyleStrategy styleBorder =
                ExcelStyleUtils.createStyleBorder();
        EasyExcel.write(response.getOutputStream(), head)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerWriteHandler(styleBorder)
                .registerConverter(new LocalDateTimeConverter())
                .autoCloseStream(Boolean.FALSE)
                .sheet("Sheet1")
                .doWrite(data);
    }

    public static <T> void exportTemplateExcel(HttpServletResponse response, String fileName, Class<T> head, List<T> data) throws IOException {
        if (data == null) {
            data = new ArrayList<>();
        }
        StringBuilder sb = new StringBuilder(fileName);
        fileName = sb.toString();
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里 URLEncoder.encode 可以防止中文乱码 当然和 easyexcel 没有关系
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");
        // 这里需要设置不关闭流
        HorizontalCellStyleStrategy styleBorder =
                ExcelStyleUtils.createStyleBorder();
        EasyExcel.write(response.getOutputStream(), head)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerWriteHandler(styleBorder)
                .registerConverter(new LocalDateTimeConverter())
                .autoCloseStream(Boolean.FALSE)
                .sheet("Sheet1")
                .doWrite(data);
    }

    /**
     * 校验文件类型
     *
     * @param fileName
     */
    public static void checkExcelFile(String fileName) {
        Objects.requireNonNull(fileName);
        // 设置允许上传文件类型
        String suffixList = "xls, xlsx";
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (suffixList.contains(suffix.trim().toLowerCase())) {
            return;
        } else {
            log.warn("checkExcelFile 错误信息：{}", "文件格式错误, 请重新上传");
            throw new CommonException(400, "文件格式错误，请重新上传");
        }
    }
}